/**
 * 
 */
package com.sinoglobal.wallet.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.app.SinoValueManager;
import com.sinoglobal.wallet.util.NetWorkUtil;
import com.sinoglobal.wallet.util.SystemBarTintManager;
import com.sinoglobal.wallet.view.DialogOfSetting;

/**
 * @author KeZhuang
 *
 */
@TargetApi(Build.VERSION_CODES.KITKAT) 
public class W_SinoBaseActivity extends FragmentActivity implements
		OnClickListener {
	protected FragmentManager mFragmentManager;

	private Dialog messageDialog; //系统的对话框
	private View mBaseActivityContainer;
	/** 标题栏总布局*/
	protected View mTemplateLayout;
	/** 标题栏左边的图片*/
	protected ImageView mTemplateLeftImg;
	/** 标题栏中间标题左下角的黑三角的图片*/
	protected ImageView wallet_title_middle_right_img;
	/** 标题栏右边的图片*/
	protected ImageView mTemplateRightImg;
	/** 标题栏右边的布局 **/
	protected View mRightLayout;
	/** 标题栏左边的文字*/
	protected TextView mTemplateLeftText;
	/** 标题栏右边的文字*/
	protected TextView mTemplateRightText;
	/** 标题栏中间的文字*/
	protected TextView mTemplateTitleText;
	/** 标题栏中间的图片*/
	protected ImageView mTemplateTitleImg;
	/** 模版的主布局*/
	private FrameLayout mTemplateContainer;
	/** 是否使用模版,true为使用,false则相反*/
	protected boolean isTemplate = true;
	/** Activity管理*/
	private static List<Activity> sActivities = new ArrayList<Activity>();
	/** 加载失败界面*/
	protected RelativeLayout mTemplateNoData;
	/** 加载图片用的对象*/
	public BitmapUtils bitmapUtils;
	/**屏幕的宽度和高度*/
	public int screenWidth;
	public int screenHeight;
	public RelativeLayout index_layout;
	private InputMethodManager mInputMethodManager;
	private Toast toast;
    public static Bitmap DEFAULT_PIC;//默认加载的图片
    public static Bitmap DEFAILT_FAIl_PIc;//默认加载的失败图片

	public TextView tv_statusbar_room;

	public static List<Activity> getActivities() {
		return sActivities;
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		if(!sActivities.contains(this)){
			sActivities.add(this);
		}
		mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		mFragmentManager = getSupportFragmentManager();
		bitmapUtils = new BitmapUtils(getApplicationContext());
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		screenWidth = metrics.widthPixels;
		screenHeight = metrics.heightPixels;
		  DEFAULT_PIC = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
	        DEFAILT_FAIl_PIc = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
		bitmapUtils.configDefaultLoadingImage(DEFAULT_PIC);
		bitmapUtils.configDefaultLoadFailedImage(DEFAILT_FAIl_PIc);
		setContentView(R.layout.wallet_sinoglobal_wallet_template);
		initTemplate();
		if(NetWorkUtil.getNetWorkInfoType(getApplicationContext())==NetWorkUtil.NONE){
	   loadError(true);
		}
		setSystemStatusBar();//设置状态栏的背景色
	}

	private void setSystemStatusBar() {
		tv_statusbar_room.post(new Runnable() {
			
			@Override
			public void run() {
				if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
					Rect rect = new Rect();
					mTemplateLayout.getWindowVisibleDisplayFrame(rect);
					// 状态栏的高度
					int statusBarHeight = rect.top;
					if(statusBarHeight!=0){
						final LayoutParams statusbarParams = tv_statusbar_room.getLayoutParams();	
						statusbarParams.height= statusBarHeight;
						tv_statusbar_room.setLayoutParams(statusbarParams);
					}
				}else{
					tv_statusbar_room.setVisibility(View.GONE);
				}
			}
		});
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
			setTranslucentStatus(true);
		}
		if(isTemplate){
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.w_c1);
		}
	}

	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams params = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if(on){
			params.flags |= bits;
		}else{
			params.flags &= ~bits;
		}
	}

	@Override
	public void onClick(View v) {
		
		
			if(NetWorkUtil.getNetWorkInfoType(getApplicationContext())==NetWorkUtil.NONE){
				loadError(true);
			}else{
				loadError(false);;
			}
		
		
	}

	/**
	 *  退出App
	 */
	public void exit(){
		for(Activity childActivity : sActivities){
			if(childActivity!=null){
				childActivity.finish();
			}
		}
		SinoValueManager.clearValue(getApplicationContext(),false);
	}

    public Fragment getFragmentByTag(String tag){
        Fragment fragment = mFragmentManager.findFragmentByTag(tag);
        return fragment;
    }

	private void initTemplate() {
		mRightLayout = findViewById(R.id.wallet_right_layout);
		mRightLayout.setOnClickListener(this);
		index_layout=(RelativeLayout) super.findViewById(R.id.wallet_index_layout);
		mTemplateContainer = (FrameLayout) super.findViewById(R.id.wallet_view_mainBody);
		mTemplateContainer.setBackgroundColor(Color.WHITE);
		mTemplateLayout = super.findViewById(R.id.wallet_titleview);
		mTemplateLeftImg = (ImageView) super.findViewById(R.id.wallet_title_left_btn_img);
		mTemplateNoData = (RelativeLayout) super.findViewById(R.id.wallet_noData);
		mTemplateNoData.setOnClickListener(this);
		tv_statusbar_room = (TextView)findViewById(R.id.wallet_tv_statusbar_room);
		wallet_title_middle_right_img = (ImageView)findViewById(R.id.wallet_title_middle_right_img);
		tv_statusbar_room = (TextView)super.findViewById(R.id.wallet_tv_statusbar_room);
		if (!isTemplate) {
			mTemplateLayout.setVisibility(View.GONE);
		}else{
			tv_statusbar_room.setVisibility(View.VISIBLE);
			mTemplateRightImg = (ImageView) super.findViewById(R.id.wallet_title_right_btn_img);
			// mTemplateRightImg.setOnClickListener(this);
			mTemplateLeftText = (TextView) super.findViewById(R.id.wallet_title_left_tv);
			mTemplateRightText = (TextView) super.findViewById(R.id.wallet_title_right_tv);
			mTemplateTitleText = (TextView) super.findViewById(R.id.wallet_title_middle_tv);
			mTemplateTitleImg = (ImageView) super.findViewById(R.id.wallet_iv_middle_title);
			mTemplateRightText.setOnClickListener(this);
			mTemplateTitleText.setOnClickListener(this);
			mTemplateLeftImg.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					finish();
					overridePendingTransition(R.anim.w_activity_on,
							R.anim.w_activity_off);
				}
			});
		}
	}


	/**
	 * 数据加载失败
	 * @param isError true是显示加载失败,false隐藏加载失败
	 */
	public void loadError(boolean isError){
		if(isError){
			hideViewForGone(mTemplateContainer);
			showView(mTemplateNoData);
		}else{
			showView(mTemplateContainer);
			hideViewForGone(mTemplateNoData);
		}
	}

	/**
	 * @author shenbingkai
	 * @methods getNetWork
	 * @description 判断有无网络
	 * @date 2015-3-4 上午11:24:04
	 * @param context
	 * @return 参数说明
	 */
	public static boolean getNetWork(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netinfo = cm.getActiveNetworkInfo();
		return null == netinfo;
	}

	/**
	 * 显示一个toast 
	 * @param message toast的内容
	 */
	public void showToast(String message) {
		showToast(message,Toast.LENGTH_SHORT);
	}
	public void showMidToast(String message) {
		showMidToast(message,Toast.LENGTH_SHORT);
	}
	
	/**
	 * 显示一个Toast
	 * @param message 吐司的内容
	 * @param time 吐司停留的时间
	 */
	public void showToast(String message,int time) {
		if (message == null) {
			return;
		}
		if(toast==null){
			toast = Toast.makeText(getApplicationContext(), message, time);
		}
		toast.setText(message);
		toast.show();
	}
	public void showMidToast(String message,int time) {
		if (message == null) {
			return;
		}
		if(toast==null){
			toast = Toast.makeText(getApplicationContext(), message, time);
		}
		toast.setText(message);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	
	/**
	 * 隐藏View方法,此方法隐藏会保留View的大小
	 * @param view 需要隐藏的View
	 */
	public void hideView(View... view){
		if(view.length>0){
			for(View viewParams : view){
				viewParams.setVisibility(View.INVISIBLE);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public <T> T findView(int resId){
		return (T)super.findViewById(resId);
	}
	
	/**
	 * 隐藏View方法,此方法隐藏不保留View的大小
	 * @param view 需要隐藏的View
	 */
	public void hideViewForGone(View... view){
		if(view.length>0){
			for(View viewParams : view){
				viewParams.setVisibility(View.GONE);
			}
		}
	}
	
	/**
	 * 显示View方法
	 * @param view 需要显示的View
	 */
	public void showView(View... view){
		if(view.length>0){
			for(View viewParams : view){
				viewParams.setVisibility(View.VISIBLE);
			}
		}
	}
	
	@Override
	public void setContentView(int layoutResID) {
		if (layoutResID == R.layout.wallet_sinoglobal_wallet_template) {
			mBaseActivityContainer = LayoutInflater.from(this).inflate(
					layoutResID, null);
			super.setContentView(mBaseActivityContainer);
		} else {
			mTemplateContainer.removeAllViews();
			View inflate = this.getLayoutInflater().inflate(layoutResID, null);
			inflate.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT));
			mTemplateContainer.addView(inflate);
		}
	}

	@Override
	public void setContentView(View view) {
		setContentView(view, null);
	}

	@Override
	public void setContentView(View view, LayoutParams params) {
		if (mTemplateContainer != null) {
			mTemplateContainer.removeAllViews();
			if (params != null) {
				mTemplateContainer.addView(view, params);
			} else {
				mTemplateContainer.addView(view);
			}
		} else {
			super.setContentView(view, params);
		}
	}
	
	/**
	 * intent封装 ,不支持参数,无参跳转
	 * @param toClsActivity 需要跳转到的activity
	 */
	public void goIntent(Class<?> toClsActivity) {
		goIntent(toClsActivity, null);
	}
	public static void intentForward(Context context, Intent intent) {
		context.startActivity(intent);
	}
	
	/**
	 * intent封装 ,支持参数携带
	 * @param toClsActivity 需要跳转到的activity 
	 * @param bundle 参数封装
	 */
	public void goIntent(Class<?> toClsActivity, Bundle bundle) {
		Intent intent = new Intent(this, toClsActivity);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
	}

	/**
	 * intent封装 ,隐式跳转
	 * @param action activity的action
	 */
	public void goIntent(String action){
		Intent intent = new Intent(action);
		startActivity(intent);
	}
	/**
	 * intent封装 携带参数隐式跳转
	 * @param action activity的action
	 */
	public void goIntent(String action, Bundle bundle){
		Intent intent = new Intent(action);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
	}

	/**
	 * 利用show和hide两个方法来切换fragment,切换的时候fragment不会被初始化<br>
	 * 本方法的条件是两个fragment必须都已经被add过
	 * @param from 需要隐藏的fragment
	 * @param to 需要显示的fragment
	 */
	public void changeFragment(Fragment to,Fragment from){
		if(!from.isAdded() && !to.isAdded() && !from.isHidden()){
			return ;
		}
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.hide(from);
		ft.show(to);
		ft.commit();
	}

	/**
	 * 添加fragment
	 * @param fragment 需要添加的fragment实例
	 * @param tag fragment的tag,通过tag可以找到该fragment
	 */
	public void addFragment(Fragment fragment,String tag){
		addFragment(fragment, -1, tag);
	}
	
	/**
	 * 添加fragment
	 * @param fragment 需要添加的fragment实例
	 * @param container 添加到哪(fragment容器)
	 * @param tag fragment的tag,通过tag可以找到该fragment
	 */
	public void addFragment(Fragment fragment,int container,String tag){
		if(fragment.isAdded()){
			return ;
		}
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		if(container!=-1){
			ft.add(container, fragment, tag);
		}else{
			ft.add(fragment, tag);
		}
		ft.commit();
	}
	/**
	 * 添加fragment
	 * @param fragment 需要添加的fragment实例
	 * @param container 添加到哪(fragment容器)
	 * @param tag fragment的tag,通过tag可以找到该fragment
	 * @param isHidden 是否隐藏 true为隐藏,false为不隐藏
	 */
	public void addFragment(Fragment fragment,int container,String tag,boolean isHidden){
		if(fragment.isAdded()){
			return ;
		}
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(container, fragment, tag);
		if(isHidden){
			ft.hide(fragment);
		}
		ft.commit();
	}
	
	/**
	 * 移除某个fragment
	 * @param fragment 需要移除的fragment实例
	 */
	public void removeFragment(Fragment fragment){
		if(!fragment.isAdded()){
			return ;
		}
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.remove(fragment);
		ft.commit();
	}

	/**
	 * 显示某一个fragment
	 * @param tag fragment的标识
	 */
	public void showFragment(String tag){
		Fragment fragment  = mFragmentManager.findFragmentByTag(tag);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		if(!fragment.isAdded()){
			throw new IllegalArgumentException("Fragment 没有被添加");
		}
		if(!fragment.isVisible()){
			ft.show(fragment);
			ft.commit();
		}
	}

	/** 隐藏fragment
	 * @param tag fragment的标识
	 */
	public void hideFragment(String tag){
		Fragment fragment  = mFragmentManager.findFragmentByTag(tag);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		if(!fragment.isAdded()){
			throw new IllegalArgumentException("Fragment 没有被添加");
		}
		if(!fragment.isHidden()){
			ft.hide(fragment);
			ft.commit();
		}
	}

	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.w_push_left_in, R.anim.w_push_left_out);
	}

	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		super.startActivityForResult(intent, requestCode);
		overridePendingTransition(R.anim.w_push_left_in, R.anim.w_push_left_out);
	}

	/**
	 * 用replace方法替换fragment
	 * @param container fragment容器
	 * @param to 要替换成的fragment
	 */
	public void replaceFragment(int container,Fragment to){
		replaceFragment(container, to, null);
	}
	
	/**
	 * 用replace方法替换fragment
	 * @param container fragment容器
	 * @param to 要替换成的fragment
	 * @param newtag fragment的新标签
	 */
	public void replaceFragment(int container,Fragment to,String newtag){
		if(to==null){
			return ;
		}
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		
		if(newtag!=null){
			ft.replace(container, to, newtag);
		}else{
			ft.replace(container, to);
		}
		if(to.isHidden()){
			ft.show(to);
		}
		ft.commit();
	}
	public void showConfirmDialog(String message, DialogInterface.OnClickListener sureListener){
		showConfirmDialog("", message, sureListener);
	}
	public void showConfirmDialog(String title, String message, DialogInterface.OnClickListener sureListener) {
		showConfirmDialog(title, message,R.string.btn_sure_text,R.string.btn_cancle, sureListener);
	}
	
	public void showConfirmDialog(String title, String message,int sure,int cancel, DialogInterface.OnClickListener sureListener){
		showConfirmDialog(title, message, getResources().getString(sure), getResources().getString(cancel), sureListener);
	}
	public void showConfirmDialog(String title, String message,String sure,String cancel, DialogInterface.OnClickListener sureListener){
		if (messageDialog != null) {
			messageDialog.dismiss();
			messageDialog = null;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton(sure, sureListener);
		builder.setNegativeButton(cancel, null);
		builder.setCancelable(true);
		messageDialog = builder.create();
		messageDialog.show();
	}
	/** 显示Dialog 提示框,无需调用dialog.dismiss方法
     * @param message dialog提示消息
     * @param listener dialog 的 点击监听
     */
    public void showDialog(Context context,String title, String message,final DialogOnClickListener listener){
        showDialog(context,title,message, null,R.color.w_black, null, R.color.w_black,true, listener);
    }
    
    public void showDialog(Context context,String title, String message,String sureText,String cancelText,final DialogOnClickListener listener){
    	showDialog(context,title,message, sureText,R.color.w_black, cancelText,R.color.w_black, true, listener);
    }
    
    public void showDialog(Context context,String title, String message,String sureText,int sureColor,String cancelText,int cancelColor ,final DialogOnClickListener listener){
    	showDialog(context,title,message, sureText, sureColor, cancelText, cancelColor, true, listener);
    }
    
    public void showDialog(Context context,String title, String message,int sureText,int sureColor,int cancelText,int cancelColor,boolean isShowCancel ,final DialogOnClickListener listener){
    	showDialog(context,title, message, getResources().getString(sureText), sureColor, getResources().getString(cancelText), cancelColor, isShowCancel, listener);
    }
    /** 显示Dialog 提示框,无需调用dialog.dismiss方法
     * @param message dialog的提示消息
     * @param sureText dialog确定按键的text文本
     * @param cancelText dialog取消按键的text文本
     * @param listener dialog的监听
     */
    public void showDialog(Context context,String title, String message,String sureText, int sureColor, String cancelText,int cancelColor,boolean isShowCancel ,final DialogOnClickListener listener){
        if(message==null){
            throw new NullPointerException("提示框消息不能为空");
        }
        if(sureText==null||sureText.equals("")){
            sureText = "确定";
        }
        if(cancelText==null||cancelText.equals("")){
            cancelText = "取消";
        }
         final DialogOfSetting mDialog = new DialogOfSetting(context);
        mDialog.setmMessage(message);
        mDialog.setmTitle(title);
        mDialog.setShowBtn(isShowCancel);
        if(!isShowCancel){
            mDialog.mConfirm.setText(sureText);
            mDialog.mConfirm.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(listener!=null){
                        listener.onSure(view);
                    }
                    mDialog.dismiss();
                }
            });
        }
        mDialog.mCancle.setText(cancelText);
        mDialog.mCancle.setTextColor(getResources().getColor(cancelColor));
        mDialog.mSure.setText(sureText);
        mDialog.mSure.setTextColor(getResources().getColor(sureColor));
//        mDialog.mSure.setBackgroundResource(sureBackColor);
//        mDialog.mSure.setBackgroundColor(sureBackColor);
        mDialog.mCancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onCancle(v);
                }
                mDialog.dismiss();
            }
        });
        mDialog.mSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onSure(v);
                }
                mDialog.dismiss();
            }
        });
        mDialog.show();
    }

    public void showNoCancelDialog(Context context,String title, String message,String sureText,final DialogOnClickListener listener){
        showDialog(context,title,message,sureText,R.color.w_black,null,R.color.w_black,false,listener);
    }

    /**
     * dialog的点击监听
     */
    public interface DialogOnClickListener{
        /** 确定回调
         */
        void onSure(View v);

        /**
         * 取消回调
         */
        void onCancle(View v);
    }
    
    /**
     * @Description: 隐藏软键盘
     */
	public void hideKeyboard() {
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	public abstract class ObServer {

	    private final String id;

	    public String getId() {
	        return id;
	    }

	    public ObServer(String id) {
	        this.id = id;
	    }

	    @Override
	    public boolean equals(Object o) {

	        if (this == o) {
	            return true;
	        }

	        if (o instanceof ObServer) {
	            ObServer o1 = (ObServer) o;
	            if (this.id.equals(o1.getId())) {
	                return true;
	            }
	        }

	        return false;
	    }

	    @Override
	    public int hashCode() {
	        return id.hashCode();
	    }
	    
	    public void onLoginSuccess(){};

	}

	
	public static CopyOnWriteArrayList<ObServer> observerList = new CopyOnWriteArrayList<ObServer>();
	
}
